/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.src.uniandes.ecos.tsp.creditscore.jpa;

import com.src.uniandes.ecos.tsp.creditscore.entity.Indagacion;
import com.src.uniandes.ecos.tsp.creditscore.jpa.exceptions.IllegalOrphanException;
import com.src.uniandes.ecos.tsp.creditscore.jpa.exceptions.NonexistentEntityException;
import com.src.uniandes.ecos.tsp.creditscore.jpa.exceptions.PreexistingEntityException;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import com.src.uniandes.ecos.tsp.creditscore.entity.Cliente;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import javax.persistence.NoResultException;

/**
 *
 * @author AndhyMao
 */
public class IndagacionJpaController {

    public IndagacionJpaController() {
        emf = Persistence.createEntityManagerFactory("com.src.uniandes.ecos.tsp.creditscore_CreditScoreEntities_jar_1.0-SNAPSHOTPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Indagacion indagacion) throws IllegalOrphanException, PreexistingEntityException, Exception {
        List<String> illegalOrphanMessages = null;
        Cliente clienteOrphanCheck = indagacion.getCliente();
        if (clienteOrphanCheck != null) {
            Indagacion oldIndagacionOfCliente = clienteOrphanCheck.getIndagacion();
            if (oldIndagacionOfCliente != null) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("The Cliente " + clienteOrphanCheck + " already has an item of type Indagacion whose cliente column cannot be null. Please make another selection for the cliente field.");
            }
        }
        if (illegalOrphanMessages != null) {
            throw new IllegalOrphanException(illegalOrphanMessages);
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Cliente cliente = indagacion.getCliente();
            if (cliente != null) {
                cliente = em.getReference(cliente.getClass(), cliente.getCliCodigo());
                indagacion.setCliente(cliente);
            }
            em.persist(indagacion);
            if (cliente != null) {
                cliente.setIndagacion(indagacion);
                cliente = em.merge(cliente);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findIndagacion(indagacion.getIndCodigo()) != null) {
                throw new PreexistingEntityException("Indagacion " + indagacion + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Indagacion indagacion) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Indagacion persistentIndagacion = em.find(Indagacion.class, indagacion.getIndCodigo());
            Cliente clienteOld = persistentIndagacion.getCliente();
            Cliente clienteNew = indagacion.getCliente();
            List<String> illegalOrphanMessages = null;
            if (clienteNew != null && !clienteNew.equals(clienteOld)) {
                Indagacion oldIndagacionOfCliente = clienteNew.getIndagacion();
                if (oldIndagacionOfCliente != null) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("The Cliente " + clienteNew + " already has an item of type Indagacion whose cliente column cannot be null. Please make another selection for the cliente field.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (clienteNew != null) {
                clienteNew = em.getReference(clienteNew.getClass(), clienteNew.getCliCodigo());
                indagacion.setCliente(clienteNew);
            }
            indagacion = em.merge(indagacion);
            if (clienteOld != null && !clienteOld.equals(clienteNew)) {
                clienteOld.setIndagacion(null);
                clienteOld = em.merge(clienteOld);
            }
            if (clienteNew != null && !clienteNew.equals(clienteOld)) {
                clienteNew.setIndagacion(indagacion);
                clienteNew = em.merge(clienteNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = indagacion.getIndCodigo();
                if (findIndagacion(id) == null) {
                    throw new NonexistentEntityException("The indagacion with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Indagacion indagacion;
            try {
                indagacion = em.getReference(Indagacion.class, id);
                indagacion.getIndCodigo();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The indagacion with id " + id + " no longer exists.", enfe);
            }
            Cliente cliente = indagacion.getCliente();
            if (cliente != null) {
                cliente.setIndagacion(null);
                cliente = em.merge(cliente);
            }
            em.remove(indagacion);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Indagacion> findIndagacionEntities() {
        return findIndagacionEntities(true, -1, -1);
    }

    public List<Indagacion> findIndagacionEntities(int maxResults, int firstResult) {
        return findIndagacionEntities(false, maxResults, firstResult);
    }

    private List<Indagacion> findIndagacionEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Indagacion as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Indagacion findIndagacion(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Indagacion.class, id);
        } finally {
            em.close();
        }
    }

    public int getIndagacionCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Indagacion as o").getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

    /**
     * 
     * @param clientCode
     * @param months
     * @return
     */
    public int getLastMonthsCreditInquiries(final Integer clientCode, final Integer months){
        int creditInquiries = 0;

        final EntityManager entityManager = getEntityManager();
        final Calendar cal = Calendar.getInstance();
        final StringBuilder jpql = new StringBuilder();

        jpql.append(" SELECT COUNT(i) FROM Indagacion i");
        jpql.append(" WHERE i.cliCodigo = :clientCode ");
        jpql.append(" AND i.indFeccon >= :begDate ");

        System.out.println("Query: " + jpql.toString());
        cal.add(Calendar.MONTH, -6);

        final Query query = entityManager.createQuery(jpql.toString());
        query.setParameter("clientCode", clientCode.intValue());
        query.setParameter("begDate", new Date(cal.getTimeInMillis()));

        try {
            creditInquiries = ((Long)query.getSingleResult()).intValue();
        } catch (NoResultException e) {
            e.printStackTrace();
        }finally{
            entityManager.close();
        }
        return creditInquiries;
    }
}
